package js.web.center.web.session;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.jetty.server.session.AbstractSessionDataStore;
import org.eclipse.jetty.server.session.SessionData;

/**
 * 
 * @author dowell
 *
 */
public class JsWebSessionDataStore extends AbstractSessionDataStore {
	public Map<String, SessionData> map = new HashMap<>();
	public boolean passivating;

	public JsWebSessionDataStore() {
		this.passivating = false;
	}

	public JsWebSessionDataStore(boolean passivating) {
		this.passivating = passivating;
	}

	@Override
	public boolean isPassivating() {
		return this.passivating;
	}

	@Override
	public boolean exists(String id) throws Exception {
		return this.map.containsKey(id);
	}

	@Override
	public SessionData load(String id) throws Exception {
		SessionData sd = this.map.get(id);
		if (sd == null) {
			return null;
		}
		SessionData sessionData = new SessionData(id, "", "", System.currentTimeMillis(), System.currentTimeMillis(),
				System.currentTimeMillis(), 0);
		sessionData.copy(sd);
		return sessionData;
	}

	@Override
	public boolean delete(String id) throws Exception {
		return (this.map.remove(id) != null);
	}

	@Override
	public void doStore(String id, SessionData data, long lastSaveTime) throws Exception {
		this.map.put(id, data);
	}

	@Override
	public Set<String> doGetExpired(Set<String> candidates) {
		HashSet<String> set = new HashSet<>();
		long now = System.currentTimeMillis();

		for (SessionData data : this.map.values()) {
			if (data.getExpiry() > 0 && data.getExpiry() <= now) {
				set.add(data.getId());
			}
		}
		return set;
	}
}
